<template>
	<view class="face-input-page">
		<!-- 顶部提示文字 -->
		<view class="header-text">请正对手机屏幕</view>
		
		<!-- 人脸录入区域 -->
		<view class="face-input-section">
			<view class="camera-container" v-if="!photoTaken">
				<!-- 人脸轮廓相机预览 -->
				<view class="face-camera-wrapper">
					<camera 
						class="camera" 
						:device-position="'front'"
						:flash="'off'"
						@initdone="onCameraInit"
						@error="onCameraError"
						@scancode="onScanCode"
					>
					</camera>
					<!-- 人脸识别椭圆框 -->
					<view class="face-oval-border" :class="{ 'active': faceDetected }">
						<!-- 十字辅助线 -->
						<view class="cross-line horizontal"></view>
						<view class="cross-line vertical"></view>
					</view>
				</view>
				
				<!-- 拍照按钮 -->
				<view class="photo-controls">
					<button class="photo-btn" @tap="takePhoto">
						<view class="photo-btn-inner" :class="{ 'detected': faceDetected }"></view>
					</button>
					<text class="photo-hint">{{ faceDetected ? '检测到人脸，可以拍照了' : '请将人脸对准圆圈' }}</text>
				</view>
			</view>
			
			<!-- 照片预览 -->
			<view class="photo-preview" v-if="photoTaken">
				<view class="face-image-wrapper">
					<image :src="photoPath" class="preview-image" mode="aspectFill"></image>
				</view>
				
				<!-- 重拍按钮 -->
				<view class="photo-controls">
					<button class="retake-btn" @tap="retakePhoto">重新拍摄</button>
				</view>
			</view>
		</view>
		
		<!-- 下一步按钮 -->
		<view class="next-btn-container">
			<button class="next-btn" @tap="nextStep" v-if="photoTaken">下一步</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import FaceDetection from '@/common/faceDetection.js'
import { uploadFile } from '@/common/api.js'

// 响应式数据
const faceDetected = ref(false)
const photoTaken = ref(false)
const photoPath = ref('')

// 相机上下文和人脸检测实例
let cameraContext = null
let faceDetector = null

// 页面加载
onMounted(async () => {
	// 初始化人脸检测器
	faceDetector = new FaceDetection()
	
	// 检查并请求相机权限
	const hasPermission = await FaceDetection.checkCameraPermission()
	if (!hasPermission) {
		await FaceDetection.requestCameraPermission()
	}
	
	// 启动人脸检测
	startFaceDetection()
})

// 页面卸载
onUnmounted(() => {
	if (faceDetector) {
		faceDetector.stopDetection()
	}
})

// 人脸检测回调处理
const handleFaceDetection = (result) => {
	if (result.detected) {
		faceDetected.value = true
	} else {
		faceDetected.value = false
	}
}

// 相机初始化完成
const onCameraInit = () => {
	console.log('相机初始化完成')
	cameraContext = uni.createCameraContext()
}

// 相机错误处理
const onCameraError = (e) => {
	console.error('相机错误:', e)
	uni.showToast({
		title: '相机启动失败',
		icon: 'none'
	})
}

// 二维码扫描（如果需要）
const onScanCode = (e) => {
	console.log('扫描结果:', e)
}

// 启动人脸检测
const startFaceDetection = () => {
	if (faceDetector && !photoTaken.value) {
		faceDetector.startDetection(handleFaceDetection, 800)
		console.log('人脸检测已启动')
	}
}

// 手动拍照
const takePhoto = () => {
	if (!cameraContext) {
		uni.showToast({
			title: '相机未准备好',
			icon: 'none'
		})
		return
	}
	
	// 移除人脸检测限制，允许用户随时拍照
	// if (!faceDetected.value) {
	// 	uni.showToast({
	// 		title: '请将人脸对准识别区域',
	// 		icon: 'none'
	// 	})
	// 	return
	// }
	
	cameraContext.takePhoto({
		quality: 'high',
		success: (res) => {
			photoPath.value = res.tempImagePath
			photoTaken.value = true
			
			// 停止人脸检测
			if (faceDetector) {
				faceDetector.stopDetection()
			}
			
			// 拍照反馈效果
			FaceDetection.createCaptureVibration()
			FaceDetection.createSuccessSound()
			
			uni.showToast({
				title: '拍照成功',
				icon: 'success'
			})
		},
		fail: (err) => {
			console.error('拍照失败:', err)
			uni.showToast({
				title: '拍照失败，请重试',
				icon: 'none'
			})
		}
	})
}

// 重新拍照
const retakePhoto = () => {
	photoTaken.value = false
	photoPath.value = ''
	faceDetected.value = false
	
	// 重新启动人脸检测
	if (faceDetector) {
		faceDetector.clearHistory()
	}
	startFaceDetection()
}

// 下一步
const nextStep = async () => {
	if (!photoPath.value) {
		uni.showToast({
			title: '请先拍照',
			icon: 'none'
		})
		return
	}
	
	uni.showLoading({
		title: '上传照片中...'
	})
	
	try {
		// 调用文件上传接口
		const uploadRes = await uploadFile(photoPath.value)
		
		if (uploadRes.code === 200) {
			uni.hideLoading()
			
			// 跳转到资料录入页面，传递照片信息
			uni.navigateTo({
				url: `/pages/my/apply_curator_submit?photoUrl=${encodeURIComponent(uploadRes.data.url)}`
			})
		} else {
			uni.hideLoading()
			uni.showToast({
				title: '照片上传失败',
				icon: 'none'
			})
		}
	} catch (error) {
		console.error('上传失败:', error)
		uni.hideLoading()
		uni.showToast({
			title: '照片上传失败，请重试',
			icon: 'none'
		})
	}
}
</script>

<style scoped>
.face-input-page {
	min-height: 100vh;
	background: #f8f9fa;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx 20rpx 40rpx;
}

.header-text {
	font-size: 32rpx;
	color: #333;
	text-align: center;
	margin-bottom: 60rpx;
	font-weight: 500;
}

.face-input-section {
	width: 100%;
	max-width: 700rpx;
	margin-bottom: 40rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.camera-container {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.face-camera-wrapper {
	position: relative;
	width: 500rpx;
	height: 500rpx;
	border-radius: 50%;
	overflow: hidden;
	background: #000;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
}

.camera {
	width: 100%;
	height: 100%;
}

.face-oval-border {
	position: absolute;
	top: -4rpx;
	left: -4rpx;
	width: calc(100% + 8rpx);
	height: calc(100% + 8rpx);
	border: 4rpx solid rgba(170, 14, 153, 0.6);
	border-radius: 50%;
	box-sizing: border-box;
	transition: all 0.3s ease;
	pointer-events: none;
}

.face-oval-border.active {
	border-color: #4CAF50;
	box-shadow: 0 0 20rpx rgba(76, 175, 80, 0.4);
}

.cross-line {
	position: absolute;
	background: rgba(170, 14, 153, 0.4);
	transition: all 0.3s ease;
}

.face-oval-border.active .cross-line {
	background: rgba(76, 175, 80, 0.6);
}

.cross-line.horizontal {
	top: 50%;
	left: 20%;
	right: 20%;
	height: 2rpx;
	transform: translateY(-50%);
}

.cross-line.vertical {
	top: 20%;
	bottom: 20%;
	left: 50%;
	width: 2rpx;
	transform: translateX(-50%);
}

.photo-controls {
	margin-top: 60rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 20rpx;
}

.photo-btn {
	width: 120rpx;
	height: 120rpx;
	background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
	border: none;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
	transition: all 0.3s ease;
}

.photo-btn:active {
	transform: scale(0.95);
}

.photo-btn-inner {
	width: 80rpx;
	height: 80rpx;
	background: #fff;
	border-radius: 50%;
	border: 4rpx solid #AA0E99;
	transition: all 0.3s ease;
}

.photo-btn-inner.detected {
	border-color: #4CAF50;
	background: rgba(76, 175, 80, 0.1);
}

.photo-hint {
	font-size: 24rpx;
	color: #666;
	text-align: center;
	transition: all 0.3s ease;
}

.retake-btn {
	padding: 20rpx 40rpx;
	background: linear-gradient(135deg, #AA0E99 0%, #8B0C7A 100%);
	color: #fff;
	border: none;
	border-radius: 50rpx;
	font-size: 28rpx;
	box-shadow: 0 6rpx 20rpx rgba(170, 14, 153, 0.3);
	transition: all 0.3s ease;
}

.retake-btn:active {
	transform: translateY(2rpx);
}

.photo-preview {
	display: flex;
	flex-direction: column;
	align-items: center;
}

.face-image-wrapper {
	width: 500rpx;
	height: 500rpx;
	border-radius: 50%;
	overflow: hidden;
	background: #000;
	box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.15);
}

.preview-image {
	width: 100%;
	height: 100%;
}

.next-btn-container {
	width: 100%;
	max-width: 600rpx;
	position: fixed;
	bottom: 60rpx;
	left: 50%;
	transform: translateX(-50%);
	padding: 0 20rpx;
}

.next-btn {
	width: 100%;
	height: 88rpx;
	background: linear-gradient(135deg, #AA0E99 0%, #8B0C7A 100%);
	color: #fff;
	border: none;
	border-radius: 44rpx;
	font-size: 32rpx;
	font-weight: 500;
	box-shadow: 0 6rpx 20rpx rgba(170, 14, 153, 0.3);
	transition: all 0.3s ease;
}

.next-btn:active {
	transform: translateY(2rpx);
}
</style>
